import { computed, h, reactive, ref } from 'vue';
import { FormRules, NButton, NSpace, NTag } from 'naive-ui';
import { Layer } from 'slash-layer';
import form from './AuthTbRoleUpdate.vue';
import httpApi from './httpApi';
import SysResourceBindPermission from './subviews/SysResourceBindPermission.vue';
import { SlashAppContext, checkAuthShow, MyTableBasicColumn, SysAppApi } from 'slash-admin';
import { AuthCodes } from '@/apis/auth-code';
import Utils from '@/utils';

/**
 * 视图控制
 */
export const vCtl = reactive({
  addBtn: computed(() => {
    return true;
  }),
  updateBtn: computed(() => {
    return true && checkedRows.value.length == 1;
  }),
  delBtn: computed(() => {
    return true && checkedRows.value.length >= 1;
  }),
});

export const initQuery = {};
export const queryForm = ref<any>(JSON.parse(JSON.stringify(initQuery)));
export const tableRef = ref<any>();

const noAllowDeleteIds = new Set<string | number>();

/**
 * 选中的数据
 */
export const checkedRows = ref<any>([]);

/**
 * 选中行
 * @param rows
 */
export async function onCheckedRowEvent(rows: any[]) {
  checkedRows.value = rows;
}

/**
 * 枚举字段
 */
export const enabledTextEnum = reactive({
  1: {
    text: '启用',
    style: 'info',
  },
  0: {
    text: '禁用',
    style: 'error',
  },
});

export function reloadTable() {
  if (tableRef.value) {
    tableRef.value.reload();
  }
}

export const getEnabledTextEnum = (key: number | string) => {
  return enabledTextEnum[key].text || `--`;
};

export const getEnabledStyleEnum = (key: number | string) => {
  return enabledTextEnum[key].style || `--`;
};
export const enabledOptions = computed(() => {
  const temp: any = [];
  Object.keys(enabledTextEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: enabledTextEnum[key].text,
    });
  });
  return temp.reverse();
});
/**
 * 允许删除枚举
 */
export const allowDelEnum = reactive({
  1: {
    text: '是',
    style: 'default',
  },
  0: {
    text: '否',
    style: 'error',
  },
});
export const allowDelOptions = computed(() => {
  const temp: any = [];
  Object.keys(allowDelEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: allowDelEnum[key].text,
    });
  });
  return temp.reverse();
});
export const isDefaultEnum = reactive({
  1: {
    text: '是',
    style: 'default',
  },
  0: {
    text: '否',
    style: 'error',
  },
});
export const isDefaultOptions = computed(() => {
  const temp: any = [];
  Object.keys(isDefaultEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: isDefaultEnum[key].text,
    });
  });
  return temp.reverse();
});

/**
 * 更新弹框
 * @param row
 */
export async function doUpdateModal(row: any) {
  if (checkedRows.value.length != 1 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value[0],
    };
  }
  await Layer.updateForm({
    title: '编辑角色',
    content: {
      component: form,
      props: { ...row },
    },
  } as any);
  await reloadTable();
}

/**
 * 新增
 * @param row
 */
export async function doSaveModal(row: any) {
  console.log('传递的数据:{}', row);
  await Layer.createForm({
    title: '新建角色',
    content: {
      component: form,
      props: {},
    },
  } as any);
  await reloadTable();
}

/**
 * 删除
 * @param row
 */
export async function doDeleteModal(row: any) {
  let ids: any[] = [];
  if (!row) {
    ids = [...(checkedRows.value as string[]).filter((id) => !noAllowDeleteIds.has(id))];
  }
  if (row) {
    ids.push(row.id);
  }

  if (ids.length == 0) {
    Layer.error('请选择要删除的且被允许删除的数据条目');
    return;
  }
  await Layer.confirm('您确定删除选中记录么');
  await httpApi.doLogicDeleteEntity(ids);
  await reloadTable();
  checkedRows.value = [];
}

/**
 * 查看表单
 * @param row
 */
export async function doReadModal(row: any) {
  if (checkedRows.value.length != 1 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value[0],
    };
  }
  await Layer.readForm({
    title: '编辑',
    content: {
      component: form,
      props: { ...row },
    },
  } as any);
}

const _optionsMap = new Map();

const _getOptionMap = async () => {
  if (_optionsMap.size) return _optionsMap;
  const msg = await SysAppApi.doSelectPageList({ pageSize: 50 } as any);
  console.log(msg);
  const result = msg.data.map((it) => {
    return { value: it.appCode, label: it.appName };
  });
  _optionsMap.set('resourceAppCode', result);
  return _optionsMap;
};

/**
 * 角色绑定权限
 * @param row
 */
export async function doBindPermissionModal(row: any) {
  await Layer.createForm({
    title: '功能授权',
    autoInfo: true,
    position: 'lg',
    content: {
      component: SysResourceBindPermission,
      props: { ...row, 'options-map': await _getOptionMap() },
    },
  } as any);
}

/**
 * 列表页面列
 */
export const tableColumns: MyTableBasicColumn[] = [
  {
    title: '选中',
    key: 'id',
    type: 'selection',
    fixed: 'left',
    width: 50,
    disabled(row: any) {
      return row.name === 'Edward King 3';
    },
  },
  {
    title: '角色名称',
    key: 'roleName',
    sorter: 'roleName',
    searchType: 'like',
    width: 150,
    searchProps: {
      type: 'text',
    },
  },
  {
    title: '角色编码',
    key: 'roleCode',
    sorter: 'roleCode',
    searchType: 'like',
    width: 150,
    searchProps: {
      type: 'text',
    },
  },
  {
    title: '是否默认',
    key: 'isDefault',
    sorter: 'isDefault',
    width: 100,
    render(row: any) {
      console.log(111);
      return h(
        NTag,
        {
          type: isDefaultEnum[row.isDefault] ? isDefaultEnum[row.isDefault].style : 'err',
        },
        isDefaultEnum[row.isDefault] ? isDefaultEnum[row.isDefault].text : 'err'
      );
    },
  },
  {
    title: '优先级',
    key: 'priorityLevel',
    sorter: 'priorityLevel',
    width: 100,
  },
  {
    title: '状态',
    key: 'enabled',
    width: 80,
    render(row: any) {
      console.log(111);
      return h(
        NTag,
        {
          type: enabledTextEnum[row.enabled] ? enabledTextEnum[row.enabled].style : 'error',
        },
        enabledTextEnum[row.enabled] ? enabledTextEnum[row.enabled].text : '未知'
      );
    },
    searchProps: {
      type: 'select',
    },
  },
  {
    title: '允许删除',
    key: 'allowDel',
    width: 100,
    render(row: any) {
      console.log(111);
      return h(
        NTag,
        {
          type: allowDelEnum[row.allowDel] ? allowDelEnum[row.allowDel].style : 'error',
        },
        allowDelEnum[row.allowDel] ? allowDelEnum[row.allowDel].text : '未知'
      );
    },
  },

  {
    title: '创建时间',
    key: 'createTime',
    width: 120,
    searchProps: {
      type: 'date-range',
    },
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'id',
    type: 'id',
    width: 160 * SlashAppContext.getCoefficient(),
    render: function (row: any) {
      if (!row.allowDel) {
        noAllowDeleteIds.add(row.id);
      } else if (noAllowDeleteIds.has(row.id)) {
        noAllowDeleteIds.delete(row.id);
      }
      return h(NSpace, [
        h(
          NButton,
          {
            onVnodeMounted: async (vNode) => {
              await checkAuthShow(vNode.el as any, AuthCodes['角色管理功能授权']);
            },
            type: 'primary',
            text: true,
            onClick: (async (row: any) => {
              await doBindPermissionModal(row);
            }).bind(null, row),
          },
          '功能授权'
        ),
        h(
          NButton,
          {
            onVnodeMounted: async (vNode) => {
              await checkAuthShow(vNode.el as any, AuthCodes['角色管理编辑']);
            },
            type: 'primary',
            text: true,
            onClick: (async (row: any) => {
              await doUpdateModal(row);
            }).bind(null, row),
          },
          '编辑'
        ),
        h(
          NButton,
          {
            onVnodeMounted: async (vNode) => {
              await checkAuthShow(vNode.el as any, AuthCodes['角色管理删除']);
            },
            show: false,
            type: 'primary',
            text: true,
            disabled: !row.allowDel,
            onClick: (async (row: any) => {
              await doDeleteModal(row);
            }).bind(null, row),
          },
          '删除'
        ),
      ]);
    },
  },
];
/**
 * 新增和更新校验规则
 */
export const formRules = reactive<FormRules>({
  roleName: [
    {
      required: true,
      validator: (rule, val) => Utils.validSpace(rule, val, '请输入角色名称'),
      trigger: 'blur',
    },
  ],
  roleCode: [
    {
      required: true,
      validator: (rule, val) => Utils.validSpace(rule, val, '请输入角色编码'),
      trigger: 'blur',
    },
  ],
});
